package 第二类.controller;

import javax.imageio.ImageIO;
import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.annotation.*;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.Random;

@WebServlet("/VcodeServlet")
public class VcodeServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        this.doPost(request, response);
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //通知浏览器不要缓存
        response.setHeader("pragma","no-cache");
        response.setHeader("cache-control","no-cache");
        response.setHeader("expires","0");

        int width=90;int height=40;
        //1.创建一对象，在内存中图片
        BufferedImage image=new BufferedImage(width,height,BufferedImage.TYPE_INT_RGB);

        //2.美化图片,填充背景色
        Graphics g=image.getGraphics();  //画饼对象
        g.setColor(Color.PINK);   //设置画饼颜色
        g.fillRect(0,0,width,height);  //填充图片的宽高
        //2.1.画边框
        g.setColor(Color.BLUE);
        g.drawRect(0,0,width-1,height-1);

        String str="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopwrstuvwxyz0123456789";
        //生成随机角标
        Random ran=new Random();
        StringBuffer sb=new StringBuffer();  //建立可变序列数组
        for(int i=1;i<=4;i++){
            int index=ran.nextInt(str.length());  //随机下标
            //获取字符
            char ch =str.charAt(index);
            sb.append(ch);
            //2.3写验证码
            g.drawString(ch+"",width/5*i,height/2);
        }
        String checkCode_session=sb.toString();

        //将验证码存入session
        request.getSession().setAttribute("checkCode_session",checkCode_session);

        //干扰线

        //将图片输出到页面展示
        ImageIO.write(image,"jpg",response.getOutputStream());
    }
}
